import random
from app import socket_io
from threading import Lock

thread = None
thread_lock = Lock()


@socket_io.on('message')
def handle_message(data):
    print('received message: ' + data)


@socket_io.on('connect', namespace='/conn')
def test_():
    global thread
    with thread_lock:
        if thread is None:
            thread = socket_io.start_background_task(target=bk_thread)


def bk_thread():
    while True:
        socket_io.sleep(3)
        socket_io.emit('server_response', {'data': random.randint(0, 100)}, namespace='/conn')
